from apps.global_config.serializer import TokenSerializer

from apps.global_config.serializer import get_global_config
from utilities.meta_view import APIViewUpdate, APIViewRetrieve, Response, Success, APIView
from rest_framework.permissions import AllowAny
from apps.warn_center.serializer import FakeRequest
from apps.account_manager.account_utils import clear_cache_token
from utilities.djconsole import djconsole


class TokenSettingsView(APIViewRetrieve, APIViewUpdate):
    serializer_class = TokenSerializer
    queryset = TokenSerializer.Meta.model.objects

    def retrieve(self):
        obj_global_config = get_global_config()
        serializer = self.get_serializer(obj_global_config)

        return Response(serializer.data)

    def update(self):
        instance = get_global_config()
        old_token_limit = instance.access_token_limit
        serializer = self.get_serializer(instance, data=self.request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        new_instance = get_global_config()
        new_token_limit = new_instance.access_token_limit
        # 如果token过期时间调整，则用户需要重新登录
        if new_token_limit != old_token_limit:
            clear_cache_token()
        return Success()


class Display(APIView):
    permission_classes = [
        AllowAny,
    ]

    def get(self, request, *args, **kwargs):
        return Response({'data': djconsole.get_license_detail(FakeRequest()).get('about', {})})


class Ashe(APIViewRetrieve):
    """
    test func
    """
    def retrieve(self):
        self.t_resave()

        return Response()

    @staticmethod
    def func():
        from models.warn import WebReceivers
        WebReceivers(**{
            'contact_name': '默认告警联系人',
            'receiver_email': "admin@default.com",
            'receiver_type': 0
        }).save()

    @staticmethod
    def t_resave():
        from models.target import TargetGroups
        from apps.target.serializer import resave_target_groups

        resave_target_groups(TargetGroups.objects.filter())
